const express = require("express");
const fs=require("fs");

//express实例
const app = express();

//bundle
const bundle=require("../dist/server/vue-ssr-server-bundle.json");
const clientManifest=require("../dist/client/vue-ssr-client-manifest.json")

//创建渲染器
const renderer = require("vue-server-renderer").createBundleRenderer(bundle,{
    runInNewContext:false,
    template:fs.readFileSync("../src/index.temp.html","utf-8"),
    clientManifest
})

function renderToString (context){
    return new Promise((resolve,reject)=>{
        renderer.renderToString(context,(err,html)=>{
            if(err){
                reject(err)
                return;
            }
            resolve(html)
        })
    })
}
app.use(express.static('../dist/client', {index: false}))

//服务端路由
app.get("*", async (req, res) => {
    try {
        const context={
            title:"sst test",
            url:req.url
        }
        //将vue实例渲染为html子字符串,这里要注意renderToString是异步函数
        const html = await renderToString(context)
        res.send(html)
    } catch (error) {
        console.log(error)
        res.status(500).send("创建失败");
    }
})
app.listen(7832, () => {
    console.log("服务器启动成功")
})